// +build !aio

package cs

import (
	"github.com/sniperHW/fly/core/compress"
	"github.com/sniperHW/fly/net/pb"
)

func (this *InboundProcessorBase) GetRecvBuff() []byte {
	return this.Buffer[this.w:]
}

func (this *InboundProcessorBase) OnData(data []byte) {
	this.w += len(data)
}

func (this *InboundProcessorBase) Unpack() (interface{}, error) {
	if this.r == this.w {
		return nil, nil
	} else {
		msg, packetSize, err := this.BaseUnpack(this.Buffer, this.r, this.w)
		if nil != msg {
			this.r += packetSize
			if this.r == this.w {
				this.r = 0
				this.w = 0
			}
		} else if nil == err {
			if packetSize > cap(this.Buffer) {
				buffer := make([]byte, sizeofPow2(packetSize))
				copy(buffer, this.Buffer[this.r:this.w])
				this.Buffer = buffer
			} else {
				//空间足够容纳下一个包，
				copy(this.Buffer, this.Buffer[this.r:this.w])
			}
			this.w = this.w - this.r
			this.r = 0
		}
		return msg, err
	}
}

func (this *InboundProcessorBase) OnSocketClose() {

}

func NewInboundProcessor(pbSpace *pb.Namespace, docompress bool) *InboundProcessor {
	receiver := &InboundProcessor{
		pbSpace: pbSpace,
	}

	receiver.InboundProcessorBase = &InboundProcessorBase{
		Buffer:     make([]byte, 64*1024),
		BaseUnpack: receiver.unpack,
	}

	if docompress {
		receiver.unCompressor = &compress.ZipUnCompressor{}
	}
	return receiver
}
